-- DarkStoneM
-- created by cheny3
-- 暗之石柱

module("DarkStoneM", package.seeall);

local dark_stone_table = {};

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    dark_stone_table = {};

    local dark_stone_CSV = get_dark_stone_CSV();
    for i = 1, #dark_stone_CSV do
        local row = dark_stone_CSV[i];

        dark_stone_table[row.id] = row;
    end
end

-- 模块初始化操作
function init()
    if not _init then
        loadCsv();
    end

    EventMgr.removeAll("DarkStoneM");

    -- 开始新回合
    CombatM.registerEndRoundCB("dark_stone_blast", whenEndRound);
end

-- 查询
function query(optionId, path)
    local m = dark_stone_table[optionId];

    if not m or not path then
        return m;
    end

    return m[path];
end

-- 回合结束
function whenEndRound()
    -- 找到暗之石柱
    local grid = findDarkStone();

    if not grid then
        -- 没有石柱
        return;
    end

    local stoneId = grid.stone_id;
    local blastRound = query(stoneId, "round");
    local round = CombatM.getRound();

    if round <= blastRound then
        -- 还未到爆炸回合
        return;
    end

    -- 玩家死亡
    ME.user:setHp(0);
    -- 延迟效果
    ME.user:die({["delay"] = 2.3});

    -- 格子设为失效
    grid:changeState(GRID_STATE_DISABLE);

    -- 抛出爆炸事件
    EventMgr.fire(event.DARK_STONE_BLAST, {["pos"] = grid:getPos()});
end

-- 找到暗之石柱
function findDarkStone()
    local grids = DungeonM.getCurrentDungeon() or {};
    for _, grid in pairs(grids) do
        if grid.type == GRID_TYPE_DARK_STONE and
            grid.state ~= GRID_STATE_DISABLE then
            return grid;
        end
    end
    return;
end

-- 解除石柱
function darkStoneDisable()
    local grid = findDarkStone();
    if not grid then
        -- 没有石柱
        return;
    end

    -- 直接置为失效
    grid:changeState(GRID_STATE_DISABLE);

    EventMgr.fire(event.DARK_STONE_DISABLE, {["pos"] = grid:getPos()});
end

-- 爆炸倒计时
function getBlastCountDown(pos)
    local grid = DungeonM.getGridByPos(pos);
    if not grid then
        return;
    end

    if grid.type ~= GRID_TYPE_DARK_STONE
        or grid.state == GRID_STATE_DISABLE then
        -- 不是暗之石柱或者失效了
        return;
    end

    local stoneId = grid.stone_id;
    local blastRound = query(stoneId, "round");
    local round = CombatM.getRound();

    return blastRound - round + 1;
end